import { getRoleList, getUserList } from '@/api/role'
import router from '@/router'
import { ref } from 'vue'

export const useTable = () => {
  const tableData = ref<any[]>([])
  const searchName = ref('')

  const isAdd = ref(false)
  const addBox = ref(false)
  const drawer = ref(false)
  const dialogTitle = ref('')

  //获取表格信息
  async function getTableData(pageName: string) {
    let data: any
    if (pageName === 'role') {
      data = await getRoleList()
    } else if (pageName === 'user') {
      data = await getUserList()
    }
    tableData.value = data.data.list
  }

  //获取角色信息
  const roleData = ref<any[]>([])
  async function getRole() {
    const roledata = await getRoleList()
    roleData.value = roledata.data.list
  }

  // 返回首页
  function jumpHome() {
    router.push('/')
  }

  //清空搜索框
  function claerInput(pageName: string) {
    searchName.value = ''
    if (pageName === 'role') {
      getTableData('role')
    } else if (pageName === 'user') {
      getTableData('user')
    }
  }

  //根据输入查找对应信息
  async function searchInput(pageName: string) {
    if (pageName === 'role') {
      const params = {
        name: searchName.value
      }
      const data = await getRoleList(params)
      tableData.value = data.data.list
    } else if (pageName === 'user') {
      const data = await getUserList({
        keyword: searchName.value
      })
      tableData.value = data.data.list
    }
  }

  //打开添加弹窗
  function openAddDialog(pageName: string) {
    addBox.value = true
    if (pageName === 'role') {
      dialogTitle.value = '添加角色'
    } else if (pageName === 'user') {
      dialogTitle.value = '添加用户'
    }
    isAdd.value = true
  }

  return {
    tableData,
    getTableData,
    getRole,
    roleData,
    jumpHome,
    claerInput,
    searchName,
    searchInput,
    openAddDialog,
    isAdd,
    addBox,
    dialogTitle,
    drawer
  }
}
